const Busboy=require('busboy')
const fs=require('fs')
const path = require('path')
const qiniu=require('qiniu')
const config=require('../api/config')
const qiniuConfig=config.qiniuConfig


// 写入目录
const mkdirsSync = (dirname) => {
    if (fs.existsSync(dirname)) {
        return true
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname)
            return true
        }
    }
    return false
}

function getSuffix (fileName) {
    return fileName.split('.').pop()
}

// 重命名
function Rename (fileName) {
    return Math.random().toString(16).substr(2) + '.' + getSuffix(fileName)
}



// 删除文件
exports.removeTemImage=function (path) {
    fs.unlink(path, (err) => {
        if (err) {
            throw err
        }
    })
}


// 上传到本地服务器
exports.uploadFile=function(ctx, options) {
    const _emmiter = new Busboy({headers: ctx.req.headers})
    const fileType = options.fileType
    const filePath = path.join(options.path, fileType)
    const confirm = mkdirsSync(filePath)
    if (!confirm) {
        return
    }
    console.log('start uploading...')
    return new Promise((resolve, reject) => {
        _emmiter.on('file', function (fieldname, file, filename, encoding, mimetype) {
            const fileName = Rename(filename)
            const saveTo = path.join(path.join(filePath, fileName))
            file.pipe(fs.createWriteStream(saveTo))
            file.on('end', function () {
                resolve({
                    imgPath: `/${fileType}/${fileName}`,
                    imgKey: fileName
                })
            })
        })

        _emmiter.on('finish', function () {
            console.log('finished...')
        })

        _emmiter.on('error', function (err) {
            console.log('err...')
            reject(err)
        })

        ctx.req.pipe(_emmiter)
    })
}


// 上传到七牛
exports.upToQiniu=function(filePath, key) {
    const accessKey = qiniuConfig.accessKey // 你的七牛的accessKey
    const secretKey = qiniuConfig.secretKey // 你的七牛的secretKey
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
    
    const options = {
        scope: qiniuConfig.scope // 你的七牛存储对象
    }
    const putPolicy = new qiniu.rs.PutPolicy(options)
    const uploadToken = putPolicy.uploadToken(mac)

    const config = new qiniu.conf.Config()
    // 空间对应的机房
    if(qiniuConfig.zoneArea=='Zone_z2'){
        config.zone = qiniu.zone.Zone_z2
    }
    else if(qiniuConfig.zoneArea=='Zone_na0') {
        config.zone = qiniu.zone.Zone_na0
    }


    const localFile = filePath
    const formUploader = new qiniu.form_up.FormUploader(config)
    const putExtra = new qiniu.form_up.PutExtra()

    // 文件上传
    return new Promise((resolved, reject) => {
        formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr, respBody, respInfo) {
            if (respErr) {
                reject(respErr)
            }
            if (respInfo.statusCode == 200) {
                resolved(respBody)
            } else {
                resolved(respBody)
            }
        })
    })

}



//获得七牛上传token
exports.upToQiniuToken=function(filename) {
    const accessKey = qiniuConfig.accessKey // 你的七牛的accessKey
    const secretKey = qiniuConfig.secretKey // 你的七牛的secretKey
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)


    let type=filename.split('.')[1]
    let name=new Date().getTime()
    let keyToOverwrite="chat/"+name+"."+type
    const options = {
        scope: qiniuConfig.scope+":"+keyToOverwrite // 你的七牛存储对象
    }
    const putPolicy = new qiniu.rs.PutPolicy(options)
    const uploadToken = putPolicy.uploadToken(mac)

    return {
        token:uploadToken,
        key:keyToOverwrite
    }

}



//建伟上传图片到七牛
exports.upToQiniuTokenForXuesheng=function (filename) {
    const accessKey = qiniuConfig.accessKey // 你的七牛的accessKey
    const secretKey = qiniuConfig.secretKey // 你的七牛的secretKey
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)


    let keyToOverwrite=filename

    let scope='alloalibazar'
    const options = {
        scope: scope+":"+keyToOverwrite // 你的七牛存储对象
    }
    const putPolicy = new qiniu.rs.PutPolicy(options)
    const uploadToken = putPolicy.uploadToken(mac)

    return {
        token:uploadToken,
        key:keyToOverwrite
    }
}


